package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * TreeOrder
 *
 * @author: lupeng6
 * @create: 2021/1/12 20:55
 */
public class TreeOrder {

    public static void main(String[] args) {
        TreeNode root = TreeMain.array2tree(new Integer[]{1, null, 2, 3});
        List<Integer> list = new ArrayList<>();
        new TreeOrder().preOrder(root, list);
        System.out.println(list);
    }

    /**
     * 前序遍历, 非递归
     *
     * @author lupeng6
     * @date 2021/1/12 21:02
     */
    public void preOrder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.push(root);
        while (!deque.isEmpty()) {
            TreeNode curr = deque.poll();
            list.add(root.val);
            if (curr.right != null) {
                deque.push(curr.right);
            }
            if (curr.left != null) {
                deque.push(curr.left);
            }
        }
    }

    /**
     * 中序遍历, 非递归
     *
     * @author lupeng6
     * @date 2021/1/12 21:02
     */
    public void inOrder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.push(root);
        while (!deque.isEmpty()) {
            TreeNode curr = deque.peek();
            while (curr.left != null) {
                deque.push(curr.left);
                curr = curr.left;
            }

            TreeNode temp = deque.pop();
            list.add(temp.val);
            if (temp.right != null) {
                deque.push(temp.right);
            }
        }
    }

}
